package com.lzb.musicplayer.activity;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.SeekBar;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.lzb.musicplayer.BaseAc;
import com.lzb.musicplayer.R;
import com.lzb.musicplayer.adapter.ListStrAdapter;
import com.lzb.musicplayer.audio.AudioPlayerManager;
import com.lzb.musicplayer.databinding.ActivityEqualizerBinding;
import com.lzb.musicplayer.utils.SpUtils;
import com.lzb.musicplayer.view.VerticalSeekBar;

import java.util.Arrays;
import java.util.List;

public class EqualizerActivity extends BaseAc<ActivityEqualizerBinding> implements View.OnClickListener {

    private VerticalSeekBar[] seekBars = new VerticalSeekBar[5];
    private AudioPlayerManager playerManager;
    private int audioSessionId;
    private List<String> list = Arrays.asList("普通", "古典", "舞曲", "平淡", "民谣", "重金属", "说唱", "爵士", "流行", "摇滚");

    @Override
    protected int onCreate() {
        return R.layout.activity_equalizer;
    }

    @Override
    protected void initView() {
        mDataBinding.ivEqualizerBack.setOnClickListener(view -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.ivOpen.setOnClickListener(this);
        mDataBinding.rlSoundMode.setOnClickListener(this);

        // 初始化音场增强控件
        playerManager = AudioPlayerManager.getInstance(EqualizerActivity.this);
        audioSessionId = playerManager.getAudioSessionId();

        setupUI();

        if (SpUtils.getInstance().getInt("openType", 0) == 1) {
            mDataBinding.ivOpen.setImageResource(R.drawable.kai);
            String string = SpUtils.getInstance().getString("fgTxt", "普通");
            mDataBinding.tvMode.setText(string);
            seekBars[0].setProgress(SpUtils.getInstance().getInt("fgSeek1", 0));
            seekBars[1].setProgress(SpUtils.getInstance().getInt("fgSeek2", 0));
            seekBars[2].setProgress(SpUtils.getInstance().getInt("fgSeek3", 0));
            seekBars[3].setProgress(SpUtils.getInstance().getInt("fgSeek4", 0));
            seekBars[4].setProgress(SpUtils.getInstance().getInt("fgSeek5", 0));
        } else {
            mDataBinding.ivOpen.setImageResource(R.drawable.guan);
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ivOpen) {//均衡器开关
            int type = SpUtils.getInstance().getInt("openType", 0);
            if (type == 0) {
                SpUtils.getInstance().putInt("openType", 1);
                mDataBinding.ivOpen.setImageResource(R.drawable.kai);
            } else {
                SpUtils.getInstance().putInt("openType", 0);
                mDataBinding.ivOpen.setImageResource(R.drawable.guan);
            }
        } else if (id == R.id.rlSoundMode) {//音效模式
            showPopupWindow(mDataBinding.tvMode, list, 1);
        }
    }

    @Override
    protected void initData() {

    }

    private void setupUI() {
        int[] seekBarIds = {R.id.sb_band1, R.id.sb_band2, R.id.sb_band3, R.id.sb_band4, R.id.sb_band5};
        for (int i = 0; i < 5; i++) {
            seekBars[i] = findViewById(seekBarIds[i]);


            // 设置频率标签（已经在XML硬编码，这里可以省略）
            // 设置SeekBar参数
            seekBars[i].setMax(30); // 对应-15dB到+15dB
            seekBars[i].setProgress(15); // 初始0dB

            final int band = i;
            seekBars[i].setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    // 转换为-15到+15范围
                    int dB = progress - 15;
                    // 设置均衡器参数（转换为毫贝单位）
                    short level = (short) (dB * 100); // 1dB = 100millibels
                    playerManager.setBandLevel((short) band, level);
                    if (SpUtils.getInstance().getInt("openType", 0) == 1) {
                        if (band == 0) {
                            SpUtils.getInstance().putInt("fgSeek1", progress);
                        } else if (band == 1) {
                            SpUtils.getInstance().putInt("fgSeek2", progress);
                        } else if (band == 2) {
                            SpUtils.getInstance().putInt("fgSeek3", progress);
                        } else if (band == 3) {
                            SpUtils.getInstance().putInt("fgSeek4", progress);
                        } else if (band == 4) {
                            SpUtils.getInstance().putInt("fgSeek5", progress);
                        }
                    }
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                }
            });
        }
    }

    public void showPopupWindow(View view, List<String> list, int type) {
        // 加载布局
        View popupView = LayoutInflater.from(EqualizerActivity.this).inflate(R.layout.popup_window_list, null);
        // 初始化PopupWindow
        PopupWindow popupWindow = new PopupWindow(
                popupView,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                true
        );
        // 设置必要属性
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        // 获取View的位置
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        // 计算显示位置
        int x = location[0];
        int y = location[1] + view.getHeight();
        // 显示PopupWindow
        popupWindow.showAtLocation(
                view,
                Gravity.NO_GRAVITY,
                x,
                y
        );
        // 处理关闭按钮点击
        RecyclerView recy = popupView.findViewById(R.id.recy);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recy.setLayoutManager(linearLayoutManager);
        ListStrAdapter listStrAdapter = new ListStrAdapter(R.layout.popup_item_list, list, this);
        recy.setAdapter(listStrAdapter);
        listStrAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                setFgData(listStrAdapter.getData().get(position));
                mDataBinding.tvMode.setText(listStrAdapter.getData().get(position));
                popupWindow.dismiss();
            }
        });


        // 可选：添加动画效果
        popupWindow.setAnimationStyle(R.style.PopupAnimation);
    }

    //设置风格
    private void setFgData(String s) {
        if (SpUtils.getInstance().getInt("openType", 0) == 1) {
            SpUtils.getInstance().putString("fgTxt", s);
        }

        if (s.equals("普通")) {// 2   0   0   0   2
            setProgress(2, 0, 0, 0, 2);
        } else if (s.equals("古典")) {//古典   5   3   -2  4   4
            setProgress(5, 3, -2, 4, 4);
        } else if (s.equals("舞曲")) {//舞曲   6   0   3   4   1
            setProgress(6, 0, 3, 4, 1);
        } else if (s.equals("平淡")) {//平淡   0   0   0   0   0
            setProgress(0, 0, 0, 0, 0);
        } else if (s.equals("民谣")) {//民谣   3   0   0   3   -1
            setProgress(3, 0, 0, 3, -1);
        } else if (s.equals("重金属")) {// 重金属  4   1   9   3   0
            setProgress(4, 1, 9, 3, 2);
        } else if (s.equals("说唱")) {//说唱   5   3   0   1   3
            setProgress(5, 3, 0, 1, 3);
        } else if (s.equals("爵士")) { //爵士   4   2   -2  2   5
            setProgress(4, 2, -2, 2, 5);
        } else if (s.equals("流行")) {//流行   -1  2   5   1   -2
            setProgress(-1, 2, 5, 1, -2);
        } else if (s.equals("摇滚")) {// 摇滚   5   3   -1  3   5
            setProgress(5, 3, -1, 3, 5);
        }
    }

    private void setProgress(int a, int b, int c, int d, int e) {
        if (SpUtils.getInstance().getInt("openType", 0) == 1) {
            SpUtils.getInstance().putInt("fgSeek1", a + 15);
            SpUtils.getInstance().putInt("fgSeek2", b + 15);
            SpUtils.getInstance().putInt("fgSeek3", c + 15);
            SpUtils.getInstance().putInt("fgSeek4", d + 15);
            SpUtils.getInstance().putInt("fgSeek5", e + 15);
        }
        seekBars[0].setProgress(a + 15);
        seekBars[1].setProgress(b + 15);
        seekBars[2].setProgress(c + 15);
        seekBars[3].setProgress(d + 15);
        seekBars[4].setProgress(e + 15);
    }

}